package proxy.dynamic.v5;

import proxy.dynamic.v3.UserMapper;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.function.BiFunction;

public class CalcServiceProxy<P , U, R> implements InvocationHandler{

    private BiFunction<P, U, R> biFunction;

    public CalcServiceProxy(BiFunction<P, U, R> biFunction){
        this.biFunction = biFunction;
    }

    public <T> T newInstance(Class<?> clazz){
        return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if(Object.class.equals(method.getDeclaringClass())){
            return method.invoke(this, args);
        }
        return execute((P)args[0], (U)args[1]);
    }

    public R execute(P p, U u){
        return biFunction.apply(p, u);
    }

}
